//
//  YSSearchViewControllerViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/12/14.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "YSSearchViewControllerViewController.h"
#import "ExtensionInfo.h"
#import "ClassRoomTableViewCell.h"
#import "ClassRoomDetailViewController.h"
#import "LiveDetailViewController.h"


@interface YSSearchViewControllerViewController ()<UISearchBarDelegate,UITextFieldDelegate>
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,weak) UISearchBar *searchBar;
@property (nonatomic,weak) UITextField *textField;
@end

@implementation YSSearchViewControllerViewController
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.textField becomeFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ClassRoomTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"ClassRoomCell"];
    
    UITextField *textField = [[UITextField alloc]init];
    textField.frame = CGRectMake(0, 0, kScreenW - 100, 30);
    textField.backgroundColor = [UIColor whiteColor];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.returnKeyType = UIReturnKeySearch;
    textField.font = [UIFont systemFontOfSize:15];
    UIImageView *searchImage = [[UIImageView alloc]init];
    searchImage.frame = CGRectMake( 15, 11, 21, 21);
    searchImage.image = [UIImage imageNamed:@"img_search"];
    textField.leftView = searchImage;
    textField.clipsToBounds = YES;
    textField.layer.cornerRadius = 15;
    [textField setPlaceholder:@"搜索你想要的"];
    textField.delegate = self;
//    [textField becomeFirstResponder];
   
    
    UISearchBar *searchBar = [[UISearchBar alloc]init];
    searchBar.placeholder = @"搜索你想要的";
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, kScreenW - 100, 40);
    searchBar.clipsToBounds = YES;
    searchBar.layer.cornerRadius = 10;
    self.searchBar = searchBar;
    
    self.navigationItem.titleView = textField;
    self.textField = textField;
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem leftBarButtonItemWithTitle:@"搜索" target:self selector:@selector(search)];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem rightBarButtonItemWithImage:[UIImage imageNamed:@"img_back"] highlighted:[UIImage imageNamed:@"img_back"] target:self selector:@selector(back)];
}
- (void)back{
    [self.textField endEditing:YES];
    [self.tableView endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh:(NSString *)searchStr
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self headerRereshing:searchStr];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self footerRereshing:searchStr];
    }];
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing:(NSString *)searchStr
{
    self.pageNo=1;
    self.type=1;
    [self creatDataList:searchStr];
}
- (void)footerRereshing:(NSString *)searchStr
{
    self.type = 2;
    if (self.isMorePage)
    {
        //添加数据
        self.pageNo++;
        [self creatDataList:searchStr];
    }
    else
    {
        [self.tableView.mj_footer endRefreshing];
    }
}
- (void)creatDataList:(NSString *)searchStr{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:@"1" forKey:@"page"];   //
    [dic setValue:KREFRESHROWS forKey:@"rows"]; //
    NSString *urlStr;
    if (self.searchType == KSearchHomeType) {
        [dic setValue:searchStr forKey:@"title"];   //推荐阅读
        urlStr = [JSPathUtil urlAppHomePageGetHomePage];
    }else if (self.searchType == KSearchClassType){
        [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //
        [dic setValue:searchStr forKey:@"courseName"];   //搜索课堂
        urlStr = [JSPathUtil urlAppCourseSearchCourse];
    }else if (self.searchType == KSearchGasStationType){
        [dic setValue:searchStr forKey:@"title"];   //推荐搜索学业加油站
        [dic setValue:[Global getUserTokenInfo] forKey:@"token"];
        [dic setValue:@"7" forKey:@"businessType"];
        urlStr = [JSPathUtil urlAppHomePageGetGasStation];
    }
    [yjNetWorkManger requestType:POST andURL:urlStr andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [self.dataArray removeAllObjects];
            if (self.searchType == KSearchClassType){
                [self.dataArray addObjectsFromArray:[ClassRoomInfo mj_objectArrayWithKeyValuesArray:response]];
            }else if (self.searchType == KSearchHomeType){
                [self.dataArray addObjectsFromArray: [ExtensionInfo mj_objectArrayWithKeyValuesArray:response[@"list"]]];
            }else {
                //                NSArray *array = [NSArray arrayWithArray:response];
                //                if (array.count) {
                [self.dataArray addObjectsFromArray: [ExtensionInfo mj_objectArrayWithKeyValuesArray:response]];
                //                }
            }
            if (self.dataArray.count <= 0 ) {
                self.noDataImageView.image = [UIImage imageNamed:@"noData.png"];
                self.noDataImageView.hidden = NO;
                self.noDataLabel.text = @"没有搜索到";
                self.noDataLabel.hidden = NO;
            }else{
                self.noDataImageView.hidden = YES;
                self.noDataLabel.hidden = YES;
            }
            
            
            if (self.type == 1)
            {
                [self.tableView.mj_header endRefreshing];
            }
            else if (self.type == 2)
            {
                [self.tableView.mj_footer endRefreshing];
            }
            [self.tableView reloadData];
        }
    }];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchType == KSearchClassType){
        ClassRoomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"ClassRoomCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.classRoomInfo = self.dataArray[indexPath.row];
        return cell;
    }
    static NSString *CellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    ExtensionInfo *extensionInfo = self.dataArray[indexPath.row];
    cell.textLabel.text = extensionInfo.title;
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchType == KSearchClassType){
        return 100;
    }
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.searchType == KSearchClassType){
        ClassRoomInfo * classRoomInfo = self.dataArray[indexPath.row];
        if ([classRoomInfo.videoType isEqualToString:@"1"]) {   //直播
            LiveDetailViewController *liveDetailVC = [[LiveDetailViewController alloc]init];
            liveDetailVC.liveDetailId = classRoomInfo.course_id;
            [self.navigationController pushViewController:liveDetailVC animated:YES];
        }else{
            ClassRoomDetailViewController *classRoomDetailVC = [[ClassRoomDetailViewController alloc]init];
            classRoomDetailVC.courseId = classRoomInfo.course_id;
            [self.navigationController pushViewController:classRoomDetailVC animated:YES];
        }
    }else{
       ExtensionInfo *extensionInfo = self.dataArray[indexPath.row];
        WebViewController *webView = [[WebViewController alloc]initWithTitle:extensionInfo.title withRequest:[NSString stringWithFormat:@"%@/sys/home/gasStation?fileEntryId=%@",URL_BASE,extensionInfo.fileEntryId]];
        [self.navigationController pushViewController:webView animated:YES];
    }
}
//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
//    [self creatDataList:searchBar.text];
//    return YES;
//}
//- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
//    [self creatDataList:searchBar.text];
//}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar endEditing:YES];
    [self setupRefresh:searchBar.text];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.textField endEditing:YES];
    [self setupRefresh:textField.text];
    return YES;
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)search{
    [self.tableView endEditing:YES];
    [self.searchBar endEditing:YES];
    [self.textField endEditing:YES];
    [self setupRefresh:self.textField.text];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
